package integral

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/pkg/common"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/hzintegralorder"
	"private-domain-overseas-service/tools/ent/predicate"
)

type IntegralOrderDao struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewIntegralOrderDao(ctx context.Context, svcCtx *svc.ServiceContext) *IntegralOrderDao {
	return &IntegralOrderDao{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// IntegralOrderByConditionPages - 分页查询积分兑换订单
func (l *IntegralOrderDao) IntegralOrderByConditionPages(cond []predicate.HzIntegralOrder, current, pageSize int64) ([]*ent.HzIntegralOrder, int, error) {
	//计算分页偏移量
	offset := common.Offset(current, pageSize)

	//查询数据
	orders, err := l.svcCtx.Orm.HzIntegralOrder.Query().Where(cond...).Order(ent.Desc(hzintegralorder.FieldID)).Offset(int(offset)).Limit(int(pageSize)).All(l.ctx)
	if err != nil {
		return nil, 0, err
	}

	//统计总数
	count, err := l.svcCtx.Orm.HzIntegralOrder.Query().Where(cond...).Count(l.ctx)
	if err != nil {
		return nil, 0, err
	}
	return orders, count, nil
}

// IntegralOrderEditStatus -设置订单发货状态
func (l *IntegralOrderDao) IntegralOrderEditStatus(id int, status int64, secret string, tx *ent.Tx) error {
	client := l.svcCtx.Orm.HzIntegralOrder
	if tx != nil {
		client = tx.HzIntegralOrder
	}
	err := client.
		UpdateOneID(id).
		SetOrderStatus(status).
		SetOrderGoodsSecret(secret).
		Exec(l.ctx)
	if err != nil {
		return err
	}
	return nil
}
